//
//  MSPet.swift
//  MichaelToy
//
//  Created by MichaelSun on 2017/11/6.
//  Copyright © 2017年 MichaelSun. All rights reserved.
//

import UIKit

struct MSPetMoveProperty {
    var speedH: Float = 0
    var speedV: Float = 0
}

class MSPet {
    ///单利写法
    static let shared = MSPet()
    private init() {
        let view = MSMainPetView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        view.backgroundColor = UIColor.black
        self.mainView = view
        self.moveProperty = MSPetMoveProperty(speedH: 1, speedV: 1)
    }
    
    //属性
    ///是否执行过初始化方法initMSPet()
    private var isInit: Bool = false
    
    ///pet主视图
    private let mainView: MSMainPetView
    
    ///移动属性
    var moveProperty: MSPetMoveProperty {
        set {
            mainView.moveProperty = newValue
        }
        get {
           return MSPetMoveProperty(speedH: 1, speedV: 1)
        }
        
    }
    
    ///计时器
    var displayLink: CADisplayLink?
    ///初始化方法
    class func initMSPet(moveProperty: MSPetMoveProperty = MSPetMoveProperty(speedH: 1, speedV: 1)) -> MSPet {
        self.shared.isInit = true
        self.shared.moveProperty = moveProperty
        return self.shared
        
    }
    
    ///显示pet,将pet放到最上层
    func show() {
        if !isInit {
           _ = MSPet.initMSPet()
        }
        let window = UIApplication.shared.windows.last!
        if !window.subviews.contains(mainView) {
            window.addSubview(mainView)
        }
        window.bringSubview(toFront: mainView)
    }
    func move() {
        if self.displayLink == nil {
            self.displayLink = CADisplayLink(target: self, selector: #selector(self.moveOneFoot))
            self.displayLink?.preferredFramesPerSecond = 30
            self.displayLink?.add(to: RunLoop.current, forMode: .commonModes)
        }
        self.displayLink?.isPaused = false
    }
    @objc private func moveOneFoot() {
        mainView.move()
    }
    
    
    


  
}
